#!/bin/bash

run_user=`whoami`

if [ 'X'$run_user != 'X''root' ]
then
    echo 'Error! should run me with root...'
    exit 1
fi

# absolute path of jdk tarball used
TARBALL_PATH=''

# absolute path to install jdk
INSTALL_HOME=''

usage() { 
  echo -e "
Usage:
  $0 [-f ARCHIVE_TARBARR_PATH] [-h INSTALL_HOME]
Common options:
  -f,  file, absolute path of archive tarball
  -h,  home, absolute path of jdk install path, default to "'`/usr/local/jdk8`'"
" 1>&2; exit 1;
}

while getopts ":f:h:" o; do
    case "${o}" in
        f)
            v=${OPTARG}
            if [ 'X'$v == 'X' ]
            then
              usage
            else
              TARBALL_PATH=${OPTARG}
            fi
            ;;
        h)
            v=${OPTARG}
            if [ 'X'$v == 'X' ]
            then
              usage
            else
              INSTALL_HOME=${OPTARG}
            fi
            ;;
        *)
            usage
            ;;
    esac
done
shift $((OPTIND-1))


if [ 'X'${TARBALL_PATH} == 'X' ]
then
    echo "Error! should give jdk tarball absolute path"
    exit 10
fi
if [ ! -f ${TARBALL_PATH} ]
then
    echo "Error! jdk tarball ${TARBALL_PATH} not found"
    exit 9
fi


if [ 'X'${INSTALL_HOME} == 'X' ]
then
    INSTALL_HOME='/usr/local/jdk8'
    echo "use default jdk install home: ${INSTALL_HOME}"    
fi
if [ -d ${INSTALL_HOME} ]
then
    echo "Error! jdk install dir ${INSTALL_HOME} exists, should clean jdk path before re-install..."
    exit 5
fi

mkdir -p ${INSTALL_HOME}

cd /tmp
tar -xzvf ${TARBALL_PATH} -C ${INSTALL_HOME} --strip-components 1

chmod -R 755 ${INSTALL_HOME}

# add JAVA_HOME env to /etc/profile
# grep if previous env exists
cnt=`cat /etc/profile | grep "^\s*JAVA_HOME" | wc -l`
if [ $cnt -lt 1 ]
then
    echo "JAVA_HOME=${INSTALL_HOME}" >> /etc/profile
else
    # if previous env exists just replace the content
    # slash '/'' is in the variables, so use different separator '|'
    sed -i "s|^\s*JAVA_HOME=.*|JAVA_HOME=${INSTALL_HOME}|g" /etc/profile
fi

# grep if previous env export exists
cnt=`cat /etc/profile | grep "^\s*export JAVA_HOME" | wc -l`
if [ $cnt -lt 1 ]
then
    echo "export JAVA_HOME" >> /etc/profile
else
    # if export exists, remove it and add new export expr at last line
    cat /etc/profile | grep -v "^\s*export JAVA_HOME" > /etc/profile_new
    cat /etc/profile_new > /etc/profile
    echo "export JAVA_HOME" >> /etc/profile
fi

source /etc/profile

# add ln for "java"
if [ -e /usr/bin/java -o -L /usr/bin/java ]
then
    rm -rf /usr/bin/java
fi

ln -s ${INSTALL_HOME}/bin/java /usr/bin/java

echo "install java in ${INSTALL_HOME} completed, can run 'java -version' and check. if you want to use JAVA_HOME in current bash, may need to execute 'source /etc/profile'"
